package com.eunion.web.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eunion.core.common.SessionUser;
import com.eunion.core.common.WebCommon;

/**
 * 自定义拦截器
 * 
 * 
 * @version 2015-4-20
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

	private Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

	/**
	 * 最后执行，可用于释放资源
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 显示视图前执行
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURI();
		if (!(url.indexOf("admin") >= 0) || url.indexOf("admin/login") >= 0 || url.equals("admin/logout")) {
			logger.debug("unauthed url :{}" , url);
			return true;
		}
		
		logger.debug("authed url :{}" , url);
		HttpSession session = request.getSession();
		Object userObj = (Object) session.getAttribute(WebCommon.SESSION_USER);
		SessionUser user = null;
		if (userObj != null && userObj instanceof SessionUser) {
			user = (SessionUser) userObj;
		}
		if (null == user) {
			String ajax = request.getHeader("Request-Method");// Request-Method":"AJAX"
			if (ajax != null && ajax.equals("AJAX")) {
				// ajax load page
				String load = request.getParameter("load");
				if (load != null && load.equals("1")) {
					// nosession.jsp
					String urlProject = request.getContextPath();
					response.sendRedirect(urlProject + "/error");
					return false;
				}
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write("{\"code\":\"-2\",\"msg\":\"会话过期，请重新登陆!\"}"); 
				return false;
			}

			// XMLHttpRequest.setRequestHeader("Request-Method","AJAX");
			// TODO 2015-05-24 区分ajax和jsp页面请求，页面直接跳转，ajax返回错误码类
			// request.getRequestDispatcher("/auth/login").forward(request,response);
			String urlProject = request.getContextPath();
			response.sendRedirect(urlProject + "/admin/login");
			return false;
		}
		return super.preHandle(request, response, handler);
	}
}
